<template>
  <div class="course-book">
    <el-form :inline="true" :model="formData" :rules="rules" ref="formData">
      <el-form-item label="书籍名称" prop="bookName">
        <el-input
          v-model="formData.bookName"
          placeholder="请填写书籍名称"
          autocomplete="off"
          :clearable="true"
        ></el-input>
      </el-form-item>
      <el-form-item label="书籍类型" prop="categoryId">
        <el-select
          v-model="formData.categoryId"
          placeholder="书籍类型"
          autocomplete="off"
          :clearable="true"
          :popper-append-to-body="false"
          style="width: 150px"
        >
          <el-option
            v-for="item in courseCategoryArray"
            :key="item.id"
            :label="item.courseCategoryName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query">查询</el-button>
        <el-button type="info" @click="clear">清空</el-button>
        <el-button type="primary" @click="dialogFormVisible = true"
          >添加书籍视频</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 添加书籍视频 -->
    <el-dialog
      title="添加书籍书籍"
      width="38%"
      :visible.sync="dialogFormVisible"
      @close="closeDialog"
    >
      <el-form
        :model="insertForm"
        :rules="insertRules"
        ref="insertForm"
        class="insertForm"
      >
        <el-form-item
          label="书籍名称"
          :label-width="formLabelWidth"
          prop="bookName"
        >
          <el-input
            v-model="insertForm.bookName"
            autocomplete="off"
            :clearable="true"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="书籍类型"
          :label-width="formLabelWidth"
          prop="categoryId"
        >
          <el-select
            v-model="insertForm.categoryId"
            autocomplete="off"
            :clearable="true"
            :popper-append-to-body="false"
            style="width: 150px"
          >
            <el-option
              v-for="item in courseCategoryArray"
              :key="item.id"
              :label="item.courseCategoryName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="封面" :label-width="formLabelWidth" prop="cover">
          <div class="insert-cover">
            <div class="cover">
              <img :src="insertForm.cover || defaultCover" alt="" />
              <el-upload
                action="zhanweifu"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="changeFile"
              >
                <span v-loading="uploadLoading"></span>
              </el-upload>
            </div>
          </div>
        </el-form-item>
        <el-form-item
          label="书籍文件"
          :label-width="formLabelWidth"
          prop="video"
        >
          <div class="insert-book">
            <el-upload
              action="zhanweifu"
              :auto-upload="false"
              :on-change="changeBookFile"
              :file-list="fileList"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传pdf文件，且不超过10M
              </div>
            </el-upload>
            <span v-loading="uploadBookLoading"></span>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="insert" :loading="insertLoading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 表格 -->
    <div class="admin-table">
      <div class="batch-btn">
        <el-button
          type="danger"
          size="mini"
          @click="batchDelete"
          v-show="this.multipleSelection.length > 0"
          >批量删除</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-loading="tableLoading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="46" align="center">
        </el-table-column>
        <el-table-column
          type="index"
          width="49"
          :index="indexConfig"
          label="序号"
          align="center"
        ></el-table-column>
        <el-table-column
          label="书籍名称"
          prop="bookName"
          width="200"
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="书籍类型"
          prop="courseCategory"
          width="150"
          align="center"
        >
        </el-table-column>
        <el-table-column label="封面" width="140" align="center">
          <template slot-scope="scope">
            <el-image
              style="width: 60px; height: 60px"
              :src="scope.row.cover"
              :preview-src-list="[scope.row.cover]"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column label="文件" width="80" align="center">
          <template slot-scope="scope">
            <el-link
              type="primary"
              :href="scope.row.bookFile"
              target="_blank"
              :underline="false"
              >下载</el-link
            >
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="160" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="修改时间" width="160" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="edit(scope.row)"
              >编辑</el-button
            >
            <el-button type="primary" size="mini" @click="viewRemark(scope.row)"
              >查看评论</el-button
            >
            <el-button type="danger" size="mini" @click="del(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        v-show="tableData.length > 0"
        background
        layout="prev, pager, next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @current-change="handleCurrentChange"
        :pager-count="7"
        style="text-align: right; margin-top: 24px"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import defaultCover from "@/assets/defaultCover.png";
import { uploadFile } from "@/api/common";
import { getAllCourseCategory } from "@/api/admin/courseCategory";
import {
  insertCourseBook,
  getCourseBookList,
  batchDeleteCourseBook,
} from "@/api/admin/courseBook";
export default {
  name: "CourseBookView",
  data() {
    return {
      // 书籍类型
      courseCategoryArray: [],
      defaultCover,
      formData: {
        bookName: "",
        categoryId: "",
      },
      insertForm: {
        bookName: "",
        categoryId: "",
        cover: "",
        bookFile: "",
      },
      rules: {
        bookName: [{ validator: this.customValidator, trigger: "blur" }],
        categoryId: [{ validator: this.customValidator, trigger: "blur" }],
      },
      insertRules: {
        bookName: [
          { required: true, message: "请输入书籍名称", trigger: "blur" },
        ],
        categoryId: [
          { required: true, message: "请选择书籍类型", trigger: "change" },
        ],
        cover: [{ required: true, message: "请上传封面", trigger: "change" }],
        bookFile: [
          { required: true, message: "请上传书籍文件", trigger: "change" },
        ],
      },
      page: 1,
      pageSize: 5,
      total: 0,
      currentPage: 1,
      dialogFormVisible: false,
      insertLoading: false,
      uploadLoading: false,
      uploadBookLoading: false,
      formLabelWidth: "120px",
      multipleSelection: [],
      tableData: [],
      tableLoading: false,
      // 文件上传列表
      fileList: [],
    };
  },
  created() {
    this.getAll();
    this.getDataList();
  },
  methods: {
    // 获取书籍类型
    async getAll() {
      const res = await getAllCourseCategory();
      this.courseCategoryArray = res.data;
    },
    // 自定义校验规则
    customValidator(rule, value, callback) {
      const { bookName, categoryId } = this.formData;
      if (!bookName && !categoryId) {
        callback(new Error("请填写信息"));
      } else {
        callback();
      }
    },
    // 分页查询
    query() {
      this.$refs.formData.validate(async (v) => {
        if (v) {
          this.page = 1;
          this.getDataList();
        }
      });
    },
    // 清空新增表单
    clear() {
      this.page = 1;
      this.currentPage = 1;
      this.$refs.formData.resetFields();
      this.getDataList();
    },
    // 关闭新增对话框的操作
    closeDialog() {
      this.insertLoading = false;
      this.fileList = [];
      this.$refs.insertForm.resetFields();
    },
    // 新增
    insert() {
      this.$refs.insertForm.validate(async (v) => {
        if (v) {
          try {
            this.insertLoading = true;
            const res = await insertCourseBook(this.insertForm);
            this.dialogFormVisible = false;
            this.getDataList();
          } finally {
            this.insertLoading = false;
          }
        }
      });
    },
    // 获取数据
    async getDataList() {
      try {
        this.tableLoading = true;
        const res = await getCourseBookList({
          ...this.formData,
          page: this.page,
          pageSize: this.pageSize,
        });
        this.tableData = res.data.records;
        this.total = res.data.total;
      } finally {
        this.tableLoading = false;
      }
    },
    // 选择文件，上传封面
    async changeFile(file) {
      // 判断格式是否正确
      const bool = this.verifyFormat(file);
      if (!bool) {
        return;
      }
      // 上传到服务器
      // console.log("上传到服务器,返回图片路径赋值给insertForm.cover");
      this.uploadLoading = true;
      try {
        let formData = new FormData();
        // 拿到存在file中的文件存放到formData中
        formData.append("file", file.raw);
        const res = await uploadFile(formData);
        this.insertForm.cover = res.data;
      } finally {
        this.uploadLoading = false;
      }
    },
    // 上传封面前校验格式
    verifyFormat(file) {
      const isJPG =
        file.raw.type === "image/jpeg" || file.raw.type === "image/png";
      const isLt2M = file.raw.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 jpg/jpeg/png 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return false;
      }
      return isJPG && isLt2M;
    },
    // 上传书籍
    async changeBookFile(file) {
      const bool = this.verifyBookFormat(file);
      if (!bool) {
        return;
      }
      if (this.fileList.length > 0) {
        this.fileList.pop();
      }
      this.uploadBookLoading = true;
      try {
        let formData = new FormData();
        // 拿到存在file中的文件存放到formData中
        formData.append("file", file.raw);
        const res = await uploadFile(formData);
        this.insertForm.bookFile = res.data;
        this.fileList.push({ name: file.raw.name });
      } finally {
        this.uploadBookLoading = false;
      }
    },
    // 上传书籍校验
    verifyBookFormat(file) {
      const isPDF = file.raw.type === "application/pdf";
      // 大小小于15M
      const isLt10M = file.raw.size / 1024 / 1024 < 10;
      if (!isPDF) {
        this.$message.error("上传视频只能是 pdf 格式!");
        return false;
      }
      if (!isLt10M) {
        this.$message.error("上传视频大小不能超过 10MB!");
        return false;
      }
      return isPDF && isLt10M;
    },
    // 配置表格索引
    indexConfig(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },
    // 当选项发生变化触发
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 分页查询
    handleCurrentChange(page) {
      this.page = page;
      this.currentPage = page;
      this.getDataList();
    },
    // 时间格式判断
    padZero(num) {
      return num < 10 ? "0" + num : num;
    },
    // 时间格式化
    formatDate(timeArray) {
      if (!timeArray) return "暂无时间";
      let year = timeArray[0];
      let month = this.padZero(timeArray[1]);
      let day = this.padZero(timeArray[2]);
      let hour = this.padZero(timeArray[3]);
      let minute = this.padZero(timeArray[4]);
      let second = this.padZero(timeArray[5]) || "00";
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },
    // 编辑
    edit(row) {
      // 可以依然跳转到layout中的router-view中
      this.$router.push({
        name: "AdminEditCourseBook",
        params: { id: row.id },
      });
    },
    // 查看评论
    viewRemark(row) {
      // 可以依然跳转到layout中的router-view中
      this.$router.push({
        name: "AdminRemarkManage",
        params: { id: row.id, type: "book" },
      });
    },
    // 删除
    async del(row) {
      this.$confirm("确定删除所选数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        const res = await batchDeleteCourseBook([row.id]);
        await this.getDataList();
      });
    },
    // 批量删除
    async batchDelete() {
      const ids = [];
      this.multipleSelection.forEach((item) => {
        ids.push(item.id);
      });
      this.$confirm("确定删除所选数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        const res = await batchDeleteCourseBook(ids);
        await this.getDataList();
      });
    },
  },
};
</script>

<style lang="less" scoped>
.course-book {
  width: 100%;
  height: 100%;
  background-color: #fff;
  .insertForm {
    width: 440px;
    .insert-cover {
      position: relative;
      width: 100%;
      height: 160px;
      .cover {
        width: 134px;
        height: 134px;
        position: relative;
        top: 50%;
        left: 21%;
        transform: translate(-50%, -50%);
        img {
          width: 100%;
          height: 100%;
          cursor: pointer;
        }
        span {
          position: absolute;
          top: 50%;
          left: 50%;
          width: 134px;
          height: 134px;
          transform: translate(-50%, -50%);
          &::before {
            content: "上传封面";
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 134px;
            height: 134px;
            background-color: rgba(0, 0, 0, 0.06);
            text-align: center;
            line-height: 134px;
            cursor: pointer;
            opacity: 0;
            visibility: hidden;
            z-index: 1;
            color: black;
          }
          &:hover::before {
            opacity: 1;
            visibility: visible;
          }
        }
      }
    }
    .insert-book {
      position: relative;
      span {
        position: absolute;
        top: 23%;
        left: 28%;
        border: 1px solid;
      }
      .el-upload__tip {
        margin-top: 0;
      }
      /deep/.el-upload-list__item:first-child {
        margin-top: 0;
      }
    }
  }
  .admin-table {
    .batch-btn {
      height: 28px;
      margin-bottom: 4px;
    }
  }
}

// 解决下拉框显示不完整问题
/deep/.el-select-dropdown__wrap.el-scrollbar__wrap {
  margin-bottom: 0 !important;
}

/*
解决单选框样式问题
  Blocked aria-hidden on an element because its descendant retained focus. 
  The focus must not be hidden from assistive technology users. 
  Avoid using aria-hidden on a focused element or its ancestor. 
  Consider using the inert attribute instead, which will also prevent focus. 
  For more details, see the aria-hidden section of the WAI-ARIA specification at Element with focus: input Ancestor with aria-hidden:
*/
/deep/ input[aria-hidden="true"] {
  display: none !important;
}
/deep/.el-radio:focus:not(.is-focus):not(:active):not(.is-disabled)
  .el-radio__inner {
  box-shadow: none !important;
}
</style>